package org.xiaohaoniu;

import org.bytedeco.javacv.*;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class RtmpPushStream {

    // 本地推送流 测试类
    public static void main(String[] args) throws IOException {
        Properties props = new Properties();
        InputStream input = RtmpPushStream.class.getClassLoader()
                .getResourceAsStream("application.properties");
        if (input == null) {
            System.err.println("找不到 application.properties 文件");
            return;
        }
        props.load(input); // 加载 properties 文件

        String cameraDevice = props.getProperty("cameraDevice");
        String code = "stream1"; //推流码
        String rtmpUrl = props.getProperty("rtmpUrl")+code; // 改成你的 RTMP 服务器地址
        String format = "dshow";
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("linux")) {
            cameraDevice = props.getProperty("cameraDeviceLinux");
            format = "video4linux2";
        }

        FFmpegLogCallback.set(); // 详细日志

        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(cameraDevice)) {

            grabber.setFormat(format); // Linux 用户使用：grabber.setFormat("v4l2");
            grabber.setImageWidth(640);
            grabber.setImageHeight(480);
            grabber.start();

            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(rtmpUrl, 640, 480, 0);
            recorder.setFormat("flv");
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFrameRate(25);
            recorder.setGopSize(50); // 每 2 秒一个关键帧（假设 25fps）
            recorder.setVideoBitrate(800_000);
            recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);

            // 推流低延迟参数
            recorder.setVideoOption("preset", "ultrafast");
            recorder.setVideoOption("tune", "zerolatency");
            recorder.setVideoOption("crf", "28"); // 画质/压缩比权衡
            recorder.setVideoOption("x264opts", "keyint=50:min-keyint=50:no-scenecut"); // 强制关键帧间隔固定


            recorder.start();

            System.out.println("推流中... 按 Ctrl+C 停止");

            Frame frame;
            while ((frame = grabber.grab()) != null) {
                recorder.record(frame);
            }

            recorder.stop();
            grabber.stop();
            System.out.println("推流结束");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
